//
//  AsyncTask.m
//  Async
//
//  Created by world on 13-6-5.
//  Copyright (c) 2013年 world. All rights reserved.
//

#import "AsyncTask.h"

@implementation AsyncTask
@synthesize task = _task;
@synthesize callback = _callback;
@synthesize target = _target;
@synthesize result = _result;
@synthesize context = _context;


-(NSMutableDictionary *)context{
    if (_context == nil) {
        _context = [[NSMutableDictionary alloc] initWithCapacity:4];
    }
    return _context;
}

-(void) main{
    if (_task && _target) {
        @autoreleasepool {
            _result = _task();
        }
    }
}

- (void (^)(void))completionBlock{
    return ^void(void){
        if (_target) {
            NSMethodSignature* signature = [_target methodSignatureForSelector:_callback];
            if([signature numberOfArguments] == ASYNC_ONE_PARAMETER_NUMBER_OF_ARGUMENTS){
                #pragma clang diagnostic push
                #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                [[NSOperationQueue mainQueue] addOperationWithBlock:^(void){
                    @autoreleasepool {
                        if (_target) {
                              [_target performSelector:_callback withObject:_result];
                        }
                    }
                }];
               #pragma clang diagnostic pop

            }else{
               #pragma clang diagnostic push
               #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                [[NSOperationQueue mainQueue] addOperationWithBlock:^(void){
                    @autoreleasepool {
                        if (_target) {
                            [_target performSelector:_callback];
                        }
                    }
                }];
             #pragma clang diagnostic pop
          }
        }
    };
}

- (void)setCompletionBlock:(void (^)(void))block{
    [NSException raise:@"setCompletionBlock is disabled, please use setCallback method instead" format: nil];
}



@end
